package edu.ruc.cluster.ui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JFileChooser;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.View;

import edu.ruc.cluster.util.ColumnLayout;
import edu.ruc.cluster.util.Const;
import edu.ruc.cluster.util.DefaultLogHandler;
import edu.ruc.cluster.util.JDKFileFilter;
import edu.ruc.cluster.util.HadoopFileFilter;
import edu.ruc.cluster.util.PropertyRetrieval;

/**
 * 2012-12-10
 * This class is used to get jdk including directory one(decompression) or source-code one(.tar.gz or bin, or rpm?)
 * Then get user's input indicating the directory where jdk moved to 
 * @author deke
 * modified: 2012-12-27
 */

@SuppressWarnings({ "serial", "unused" })
public class JdkPane extends JPanel {

	private DefaultLogHandler logHandler = null;
	private JPanel dirPane = null;
	private JPanel installPane = null;
	
	private JPanel hadoopDirPane = null;
//	private JPanel hadoopInsPane = null;
	
	/* //Variables for hadoop Panel
	private JTextField hadoopFileText = null;
	private JPanel hadoopFilePanel = null;
	private JButton hadoopButton = null;
	private JFileChooser hadoopfc = null;
	private File hadoopfile = null;
	*/
	
	private JPanel filePanel = null;
	private JTextField fileText = null;
	private JButton jdkButton = null;
	private JFileChooser jdkfc = null;
	private File jdkfile = null;
	
	private JPanel inslower = null;
	private JPanel insInput = null;
	private JLabel installLabel = null;
	private JTextField installText = null;
	
	private Border loweredBorder = null;
	private static Dimension HGAP10 = null;
	private static String FILE_LABEL = "Choose File";
//			"<html>Choose File:</html>";
	private static String DIR_LABEL = "Choose Directory:";
//			"<html>Choose Directory:</html>";
	
	private static String INPUT_DIR = "please input directory:";
//			"<html>please input directory:<html>";
	private static String DEFAULT_DIR = "JDK will be installed this directory:";
//			"<html>JDK will be installed this directory:</html>";
	
	private static int ncolumns = 15;
	
	private int label1height = 0;
	private int label2height = 0;
	private int maxLabelWidth = 150;
	
	public JdkPane(){
	}
	public void constructPane(){
		logHandler = DefaultLogHandler.getInstance();
		loweredBorder = new CompoundBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED),
	            new EmptyBorder(5,5,5,5));
		HGAP10 = new Dimension(10, 1);
			 
		setupDirPanel();
		setupInstallPanel();	
//		setupHadoopDirPanel();
		
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
//		setLayout(new FlowLayout(FlowLayout.LEFT));
		this.add(dirPane);
		this.add(installPane);
//		this.add(hadoopDirPane);
			// Add hadoop Panel here!
		this.setVisible(true);
	}
	
	/**
	 *  choose jdk: can either be a directory or install file(.bin, .rpm or .tar.gz)
	 *  -------caption-------
	 *  ------end caption----
	 *  -------choose--------
	 *  ----p1---- ----filePanel----
	 *  - (yes)  - - select - 
	 *  - (no)   - - text   -
	 *  --end p1-- --end filePanel--
	 *  ----end choose-------
	 */
	private void setupDirPanel()
	{
		dirPane = new JPanel(new ColumnLayout());
//		filePathLabel = new JLabel("");		
		fileText = new JTextField(ncolumns);
		fileText.setEditable(false);
		jdkButton = new JButton("select");
		jdkButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				int state=jdkfc.showOpenDialog(null);//open select dialog
				if(state==1){
					return;//cancel
				}
				else{
					jdkfile =jdkfc.getSelectedFile();//f is selected directory
					fileText.setText(jdkfile.getAbsolutePath());
				}
				repaint();
			}
		});
		jdkfc = new JFileChooser();
		jdkfc.setCurrentDirectory(new File("~/"));
		
		JLabel caption = new JLabel("<html>Do you have an installed JDK directory?</html>");
		caption.setFont(new Font("SansSerif.bold", Font.ITALIC, 16));
		caption.setForeground(Color.RED);
		
		JPanel choose = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
//  		choose.setLayout(new BoxLayout(choose, BoxLayout.X_AXIS));
//		choose.setLayout(new GridLayout(1, 2, 20, 20));
  		
		JPanel p1 = createVerticalPanel(false);
		p1.setBorder(new CompoundBorder(
                new TitledBorder(
                  null, " ",
                  TitledBorder.LEFT, TitledBorder.TOP), new EmptyBorder(5, 5, 5, 5))
				);  		

		ButtonGroup g = new ButtonGroup();
		JRadioButton 
				rb1 = new JRadioButton("Yes", false),
				rb2 = new JRadioButton("No", false);
		
		ActionListener dirAction = new ActionListener(){
			public void actionPerformed(ActionEvent e){
				
				if(label1height == 0){
					String str = DIR_LABEL.length() > FILE_LABEL.length() ? DIR_LABEL : FILE_LABEL;
					JLabel tmp = new JLabel(str);
					View v = BasicHTML.createHTMLView(tmp, tmp.getText());		 
					v.setSize(maxLabelWidth, Integer.MAX_VALUE);
					label1height = (int) v.getMinimumSpan(View.Y_AXIS); 
				}	
//				filePathLabel.setPreferredSize(new Dimension(maxLabelWidth, label1height));
				
				if(((JRadioButton)e.getSource()).getText().equals("Yes")){
					// choose directory
//					filePathLabel.setText(DIR_LABEL);
					jdkfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//can only choose directory
					filePanel.setBorder(new TitledBorder(DIR_LABEL));
					filePanel.setVisible(true);
					logHandler.info("Only directory");
				}else{
					// choose .bin or .rpm or .tar.gz
//					filePathLabel.setText(FILE_LABEL);
					jdkfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
					jdkfc.setFileFilter(new JDKFileFilter());
					filePanel.setBorder(new TitledBorder(FILE_LABEL));
					filePanel.setVisible(true);
					logHandler.info("Only certain kind of file");
				}
			}
		};
		filePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
		
		rb1.addActionListener(dirAction);
		rb2.addActionListener(dirAction);
		g.add(rb1);
		g.add(rb2);
		
		p1.add(rb1);
		p1.add(Box.createRigidArea(HGAP10));
		p1.add(rb2);
		
//		filePanel.add(filePathLabel);
		filePanel.add(fileText);
		filePanel.add(jdkButton);
		filePanel.setVisible(false);
		
		choose.add(p1);
		choose.add(filePanel);
		
		dirPane.add(caption);
		dirPane.add(choose);
	}
	
	/**
	private void setupHadoopDirPanel(){		
		
//		hadoopDirPane = new JPanel(new ColumnLayout());
		hadoopDirPane = new JPanel(new GridLayout(1, 2, 0, 0));
//		hadoopDirPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 0));
		hadoopFileText = new JTextField(ncolumns);
		hadoopFileText.setEditable(false);
		hadoopButton = new JButton("select");
		hadoopButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				int state=hadoopfc.showOpenDialog(null);//open select dialog
				if(state==1){
					return;//cancel
				}
				else{
					hadoopfile = hadoopfc.getSelectedFile();//f is selected directory
					hadoopFileText.setText(hadoopfile.getAbsolutePath());
				}
				repaint();
			}
		});
		hadoopfc = new JFileChooser();
		hadoopfc.setCurrentDirectory(new File("~/"));
		
		JLabel caption = new JLabel("<html>Do you have Hadoop directory?</html>");
		caption.setFont(new Font("SansSerif.bold", Font.ITALIC, 16));
		caption.setForeground(Color.RED);
		
		JLabel caption2 = new JLabel("<html>Enter the folder to install hadoop</html>");
		caption2.setFont(new Font("SansSerif.bold", Font.ITALIC, 16));
		caption2.setForeground(Color.RED);
		
		JPanel choose = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
//  		choose.setLayout(new BoxLayout(choose, BoxLayout.X_AXIS));
//		choose.setLayout(new GridLayout(1, 2, 20, 20));
  		
		JPanel p1 = createVerticalPanel(false);
		p1.setBorder(new CompoundBorder(
                new TitledBorder(
                  null, " ",
                  TitledBorder.LEFT, TitledBorder.TOP), new EmptyBorder(5, 5, 5, 5))
				);  		

		ButtonGroup g = new ButtonGroup();
		JRadioButton 
				rb1 = new JRadioButton("Yes", false),
				rb2 = new JRadioButton("No", false);
		
		ActionListener dirAction = new ActionListener(){
			public void actionPerformed(ActionEvent e){
				
				if(((JRadioButton)e.getSource()).getText().equals("Yes")){
					// choose directory
					hadoopfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//can only choose directory
					hadoopFilePanel.setBorder(new TitledBorder(DIR_LABEL));
					hadoopFilePanel.setVisible(true);
					logHandler.info("Only directory");
				}else{
					// hadoopXXXX.tar.gz
					hadoopfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
					hadoopfc.setFileFilter(new HadoopFileFilter());
					hadoopFilePanel.setBorder(new TitledBorder(FILE_LABEL));
					hadoopFilePanel.setVisible(true);
					logHandler.info("Only certain kind of file");
				}
			}
		};
		hadoopFilePanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
		
		rb1.addActionListener(dirAction);
		rb2.addActionListener(dirAction);
		g.add(rb1);
		g.add(rb2);
		
		p1.add(rb1);
		p1.add(Box.createRigidArea(HGAP10));
		p1.add(rb2);
		
		hadoopFilePanel.add(hadoopFileText);
		hadoopFilePanel.add(hadoopButton);
		hadoopFilePanel.setVisible(false);
		
		choose.add(p1);
		choose.add(hadoopFilePanel);
		
		JPanel choose2 = new JPanel(new FlowLayout(FlowLayout.CENTER, 50, 10));
		JPanel dirPane = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
//		JPanel.dirPane = new GridLayout(1,1);
		dirPane.setBorder(new TitledBorder(" "));
		dirPane.add(new JTextField(ncolumns));
		choose2.add(dirPane);
		
		JPanel left = new JPanel(new ColumnLayout());
		left.add(caption);
		left.add(choose);
		JPanel right = new JPanel(new ColumnLayout());
		right.add(caption2);
		right.add(choose2);
		
		hadoopDirPane.add(left);
		hadoopDirPane.add(BorderLayout.WEST, right);
//		hadoopDirPane.add(caption);
//		hadoopDirPane.add(caption2);
//		hadoopDirPane.add(choose);
//		hadoopDirPane.add(dirPane);
		
	}
	**/
	
	/**
	 * Used for install jdk
	 */
	private void setupInstallPanel(){
		
		installPane = new JPanel(new ColumnLayout());
		JLabel caption = new JLabel("<html>Do you want to specify the directory " +
				"for jdk to install?</html>");
		caption.setFont(new Font("SansSerif.bold", Font.ITALIC, 16));
		caption.setForeground(Color.RED);
		
		inslower = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 0));
		JPanel p1 = createVerticalPanel(false);
		p1.setBorder(new CompoundBorder(
                new TitledBorder(
                  null, " ",
                  TitledBorder.LEFT, TitledBorder.TOP), new EmptyBorder(5, 5, 5, 5))
				);  		

		ButtonGroup g = new ButtonGroup();
		JRadioButton 
				rb1 = new JRadioButton("Yes", false),
				rb2 = new JRadioButton("No", false);
		ActionListener dirAction = new ActionListener(){
			public void actionPerformed(ActionEvent e){
				
				if(((JRadioButton)e.getSource()).getText().equals("Yes")){
					// choose directory
					jdkfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//can only choose directory
					setInstalledPanel(true);
				}else{
					// given the default directory
					setInstalledPanel(false);
				}
			}
		};
		insInput = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
		insInput.setVisible(false);
		rb1.addActionListener(dirAction);
		rb2.addActionListener(dirAction);
		g.add(rb1);
		g.add(rb2);
		p1.add(rb1);
		p1.add(Box.createRigidArea(HGAP10));
		p1.add(rb2);
		inslower.add(p1);
		inslower.add(insInput);
		installPane.add(caption);
		installPane.add(inslower);
	}
	
	/*
	 * Called by setupInstallPanel():
	 * setup jdk install panel
	 * @param Custonerized: whether the user what to customerize the install path or not
	 */
	private void setInstalledPanel(boolean Customerized){
		
		insInput.removeAll();
		
		if(Customerized == true){
			insInput.setBorder(new TitledBorder(INPUT_DIR));
			if(installLabel == null)
				installLabel = new JLabel(INPUT_DIR);
			else 
				installLabel.setText(INPUT_DIR);
			installText = new JTextField(ncolumns);
		}else{
			insInput.setBorder(new TitledBorder(DEFAULT_DIR));
			if(installLabel == null)
				installLabel = new JLabel(DEFAULT_DIR);
			else
				installLabel.setText(DEFAULT_DIR);
			installText = new JTextField(ncolumns);
			installText.setText("/usr/java/");
			installText.setEditable(false);
		}
		if(label2height == 0){
			String text = INPUT_DIR.length() > DEFAULT_DIR.length() ? INPUT_DIR : DEFAULT_DIR;
			JLabel tmp = new JLabel(text);
			View v = BasicHTML.createHTMLView(tmp, tmp.getText());		 
			v.setSize(maxLabelWidth, Integer.MAX_VALUE);
			label2height = (int) v.getMinimumSpan(View.Y_AXIS); 
		}	
		installLabel.setPreferredSize(new Dimension(maxLabelWidth, label2height));
				
//		insInput.add(installLabel);
//		insInput.setSize(200, 20);
		insInput.add(installText);
		
//		JTextField tmp = new JTextField(jdkButton.getWidth());
//		logHandler.info("Button size: " + jdkButton.getWidth());
//		JTextArea tmp = new JTextArea(1, jdkButton.getWidth());
//		tmp.setVisible(false);
//		insInput.add(tmp);
//		tmp.setVisible(false);
			// Screw FlowLayout!!!!!!!!!!!!
		JLabel tmp = new JLabel("                 ");  // used for align select button
//		String content = "";
//		int width = jdkButton.getWidth();
//		logHandler.info("button width: " + width);
//		int count = 10;
//		while(tmp.getWidth() < width){
//			logHandler.info("tmp width: " + tmp.getWidth());
//			logHandler.info("content length: " + content.length());
//			content += " ";
//			tmp.setText(content);
//			count --;
//			if(count == 0)
//				break;
//		}
		insInput.add(tmp);
		
		insInput.setVisible(true);
		insInput.updateUI();
	}
	
	/*
	 * get a vertical Panel
	 */ 
	private JPanel createVerticalPanel(boolean threeD) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.setAlignmentY(TOP_ALIGNMENT);
        p.setAlignmentX(LEFT_ALIGNMENT);
        if(threeD) {
            p.setBorder(loweredBorder);
        }
        return p;
    }
	
	private JPanel createHorizontalPanel(boolean threeD) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setAlignmentY(TOP_ALIGNMENT);
        p.setAlignmentX(LEFT_ALIGNMENT);
        if(threeD) {
            p.setBorder(loweredBorder);
        }
        return p;
    }
	
	public void store(){
		PropertyRetrieval pr = new PropertyRetrieval(Const.CONFIG_FILE);
		pr.putString(Const.JDK_DST_TAG, installText.getText().toString().trim());
		pr.putString(Const.JDK_SRC_TAG, jdkfile.getAbsolutePath());
		
		/*
		try{
			BufferedWriter writor = new BufferedWriter(new FileWriter(new File(Const.CONFIG_FILE)));
			writor.write(Const.JDK_DST_TAG + Const.LINE_SEPERATOR + installText.getText().toString().trim() + "\n");
			writor.write(Const.JDK_SRC_TAG + Const.LINE_SEPERATOR + jdkfile.getAbsolutePath() + "\n");
			writor.close();
		}catch(IOException e){
			logHandler.error(this.getClass().getSimpleName() + e.getMessage(), e);
		}
		*/
	}
	public boolean ok(){
		String dir = installText.getText().trim();
		if(dir.isEmpty() == false && dir.matches("(/\\S+)*/?") 
				&& jdkfile != null && jdkfile.getAbsolutePath().matches("(/\\S+)*/?"))
			return true;
		else 
			return false;
	}
}
